﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace M.ShopMachine.Write.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        /// <summary>
        /// 单文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpFile(IFormFile file)
        {
            string path = Directory.GetCurrentDirectory() + @"/wwwroot/Image/" + file.FileName;
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            return Ok(new { code = 0, msg = "文件上传成功", data = file.FileName });
        }

        /// <summary>
        /// 多文件上传
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpFiles(IFormFile[] files)
        {
            if (files == null || files.Length == 0)
            {
                return BadRequest("未上传文件");
            }

            foreach (var file in files)
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Image", file.FileName);
                // 检查目录是否存在，如果不存在则创建
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }

                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(fs);  // 使用 CopyToAsync 异步操作
                    await fs.FlushAsync();
                }
            }

            return Ok(new { code = 0, message = "文件上传成功", files = files.Select(f => f.FileName) });
        }
    }
}
